/*
发货渠道14
*/
<template>
  <div class="app-page">
    <!-- 操作菜单区 -->
    <my-header>
      <el-button type="primary" @click="handleAddUpdate()" v-repeatClick>添加</el-button>
      <el-button @click="handleBeforeUpdate" v-repeatClick>修改</el-button>
      <el-button @click="enabled(false)">禁用</el-button>
      <el-button @click="enabled(true)">启用</el-button>
      <el-button @click="view" v-repeatClick>查看</el-button>
      <el-button @click="getChannel" v-repeatClick>刷新</el-button>
      <el-button type="danger" @click="delChannel" v-repeatClick>删除</el-button>
    </my-header>

    <!-- 列表区 -->
    <el-card  style="flex: 1;">
      <div class="app-page">
        <div class="content-flex">
          <div>
            <el-form ref="search" :model="search" inline size="small">
              <el-form-item label="" prop="info">
                <el-input
                  placeholder="搜索:渠道名称"
                  v-model="search.info"
                  clearable
                ></el-input>
              </el-form-item>
              <el-form-item label="" prop="autoSplitToBatch">
                <el-select
                  clearable
                  v-model="search.autoSplitToBatch"
                  placeholder="自动分批"
                  style="width: 100px"
                >
                  <el-option label="是" :value="true"></el-option>
                  <el-option label="否" :value="false"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="" prop="idCardNeeded">
                <el-select
                  clearable
                  v-model="search.idCardNeeded"
                  style="width: 100px"
                  placeholder="身份证">
                  <el-option label="需要" :value="true"></el-option>
                  <el-option label="不要" :value="false"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="" prop="enabled">
                <el-select
                  clearable
                  v-model="search.enabled"
                  style="width: 100px"
                  placeholder="是否启用">
                  <el-option label="是" :value="true"></el-option>
                  <el-option label="否" :value="false"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="创建时间" prop="date">
                <el-date-picker
                  v-model="search.date"
                  type="daterange"
                  value-format="yyyy-MM-dd"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期">
                </el-date-picker>
              </el-form-item>
              <el-form-item label="" prop="">
                <el-button type="primary" round @click="getChannel">搜索</el-button>
                <el-button
                  type="warning"
                  round
                  @click="$refs.search.resetFields()"
                >重置</el-button>
              </el-form-item>
            </el-form>
          </div>
        </div>
        <!-- 列表区 -->
        <div style="flex: 1">
          <el-table
            height="100%"
            :data="data"
            border
            stripe
            highlight-current-row
            ref="multipleTable"
            @row-dblclick="handleRowDbclick"
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="index" width="55" align="center">
            </el-table-column>
            <el-table-column type="selection" width="55" align="center">
            </el-table-column>
            <el-table-column label="渠道名称" prop="channelName">
              <template slot-scope="scope">
                <div class="tdItem">
                  <el-link @click="handleRowDbclick(scope.row)">{{ scope.row.channelName }}</el-link>
                </div>
                <div class="tdItem">
                  单批重量 {{scope.row.minWeight}} ~ {{scope.row.maxWeight}}
                </div>
              </template>
            </el-table-column>
            <el-table-column label="所属门店" prop="storeName"  align="center">
              <template slot-scope="scope">
                {{scope.row.storeName.join(',')}}
              </template>
            </el-table-column>
            <el-table-column label="商品资费类型" prop="channelCostInfos"  align="center" :formatter="getChannelCostInfos">
            </el-table-column>
            <el-table-column label="自动分批" prop="autoSplitToBatch"  align="center" sortable>
              <template slot-scope="scope">
                <span style="font-size: 20px">
                  <i
                    class="el-icon-circle-check"
                    style="color: #67c23a"
                    v-if="scope.row.autoSplitToBatch"
                  ></i>
                  <i
                    class="el-icon-circle-close"
                    style="color: #f56c6c"
                    v-else
                  ></i>
                </span>
              </template>
            </el-table-column>
            <el-table-column label="身份证" prop="idCardNeeded"  align="center" sortable>
              <template slot-scope="scope">
                <span style="font-size: 20px">
                  <i
                    class="el-icon-circle-check"
                    style="color: #67c23a"
                    v-if="scope.row.idCardNeeded"
                  ></i>
                  <i
                    class="el-icon-circle-close"
                    style="color: #f56c6c"
                    v-else
                  ></i>
                </span>
              </template>
            </el-table-column>
            <el-table-column label="发货日" prop="deliveryDate" sortable width="400px">
              <template slot-scope="scope">
                {{scope.row.deliveryDate.join(' ')}}
              </template>
            </el-table-column>
            <el-table-column label="启用" prop="enabled" align="center" sortable>
              <template slot-scope="scope">
                <span style="font-size: 20px">
                  <i
                    class="el-icon-circle-check"
                    style="color: #67c23a"
                    v-if="scope.row.enabled"
                  ></i>
                  <i
                    class="el-icon-circle-close"
                    style="color: #f56c6c"
                    v-else
                  ></i>
                </span>
              </template>
            </el-table-column>
            <el-table-column label="创建时间" sortable prop="createTime" align="center" width="200">
            </el-table-column>
          </el-table>
        </div>
        <!-- 分页区 -->
        <div style="margin-top: 10px">
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes="[20, 50, 100, 200, 500, 1000]"
            :page-size="pageSize"
            background
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
          >
          </el-pagination>
        </div>
      </div>
    </el-card>
    <!-- 添加发货渠道信息 -->
    <el-dialog
      v-dialog-drag
      :title="title + '发货渠道'"
      :visible.sync="dialogFormVisible"
      :close-on-click-modal="false"
      @close="restForm"
      width="1000px"
    >
      <el-form
        size="small"
        :model="baseForm"
        label-position="left"
        label-width="120px"
        ref="baseForm"
        :rules="baseFormRules"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item prop="storeName" label="所属门店">
              <el-select
                ref="select"
                multiple
                filterable
                style="width: 100%"
                v-model="baseForm.storeId"
                @change="handleStoreChange"
                placeholder="请选择所属门店">
                <el-option
                  v-for="item in stores"
                  :key="item.id"
                  :value="item.id"
                  :label="item.name"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="channelName" label="渠道名称">
              <el-input v-model="baseForm.channelName" placeholder="请输入渠道名称"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item prop="minWeight" label="每批最小重量">
              <el-input v-model="baseForm.minWeight" placeholder="请输入每批最小重量"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-row :gutter="20">
              <el-col :span="8">
                <el-form-item prop="phoneRepeatAble" label="允许电话重复">
                  <el-checkbox v-model="baseForm.phoneRepeatAble"></el-checkbox>
                </el-form-item>
              </el-col>
              <el-col :span="16">
                <el-form-item prop="phoneRepeatLimit" label="电话最大重复次数" label-width="125px">
                  <el-input v-model="baseForm.phoneRepeatLimit" placeholder="请输入电话最大重复次数"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item prop="maxWeight" label="每批最大重量">
              <el-input v-model="baseForm.maxWeight" placeholder="请输入每批最大重量"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-row :gutter="20">
              <el-col :span="8">
                <el-form-item prop="nameRepeatAble" label="允许姓名重复">
                  <el-checkbox v-model="baseForm.nameRepeatAble"></el-checkbox>
                </el-form-item>
              </el-col>
              <el-col :span="16">
                <el-form-item prop="nameRepeatLimit" label="姓名最大重复次数" label-width="125px">
                  <el-input v-model="baseForm.nameRepeatLimit" placeholder="请输入姓名最大重复次数"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item prop="deliveryDate" label="发货日">
              <el-select
                style="width: 100%"
                placeholder="请选择发货日"
                multiple
                v-model="baseForm.deliveryDate"
              >
                <el-option
                  v-for="item in [
                          '星期一',
                          '星期二',
                          '星期三',
                          '星期四',
                          '星期五',
                          '星期六',
                          '星期日',
                        ]"
                  :key="item"
                  :label="item"
                  :value="item"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-row :gutter="20">
              <el-col :span="8">
                <el-form-item prop="addressRepeatAble" label="允许地址重复">
                  <el-checkbox v-model="baseForm.addressRepeatAble"></el-checkbox>
                </el-form-item>
              </el-col>
              <el-col :span="16">
                <el-form-item prop="addressRepeatLimit" label="地址最大重复次数" label-width="125px">
                  <el-input v-model="baseForm.addressRepeatLimit" placeholder="请输入地址最大重复次数"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item prop="note" label="备注">
              <el-input v-model="baseForm.note" placeholder="备注" type="textarea"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-table :data="baseForm.channelCostInfos" border>
          <el-table-column label="操作" align="center" width="80">
            <template slot-scope="scope">
              <el-button
                type="danger"
                circle
                icon="el-icon-close"
                @click="deleteGoods(scope.$index)"
              ></el-button>
            </template>
          </el-table-column>
          <el-table-column label="商品收费类型">
            <template slot-scope="scope">
              <el-select v-model="scope.row.goodsCostType" clearable filterable @change="handleGoodsChange(scope.row)">
                <el-option v-for="goods in baseFormOptions.allGoods" :key="goods.id" :value="goods.id" :label="goods.name"></el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="批内商品数量最小占比(%)" prop="minGoodNumPop" width="200">
            <template slot-scope="scope">
              <el-input v-model="scope.row.minGoodNumPop"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="批内商品数量最大占比(%)" prop="maxGoodNumPop" width="200">
            <template slot-scope="scope">
              <el-input v-model="scope.row.maxGoodNumPop"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="每单内商品最小个数">
            <template slot-scope="scope">
              <el-input-number v-model="scope.row.minGoodsNum"  controls-position="right" style="width: 100%" :min="1"></el-input-number>
            </template>
          </el-table-column>
          <el-table-column label="每单内商品最大个数">
            <template slot-scope="scope">
              <el-input-number v-model="scope.row.maxGoodsNum"  controls-position="right" style="width: 100%" :min="1"></el-input-number>
            </template>
          </el-table-column>
        </el-table>
        <div style="text-align: right; margin-top: 10px">
          <el-link type="primary" :underline="false" @click="addGoods">
            <el-button icon="el-icon-plus" type="primary" circle>
            </el-button>
            添加商品收费类型
          </el-link>
        </div>
        <el-row :gutter="20" style="margin-top:30px">
          <el-col :span="24" style="text-align: right">
            <el-form-item>
              <el-checkbox v-model="baseForm.idCardNeeded">申报前是否需要身份证</el-checkbox>
              <el-checkbox v-model="baseForm.autoSplitToBatch">是否自动分批</el-checkbox>
              <el-checkbox v-model="baseForm.enabled">启用</el-checkbox>
              <el-button style="margin-left: 10px" @click="restForm">重置</el-button>
              <el-button type="primary" @click="submit" v-if="title!='查看'">保存</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
let search = {
  //搜索:渠道名称
  info:'',
  //是否自动审批
  autoSplitToBatch:'',
  //是否需要身份证
  idCardNeeded:"",
  //是否启用
  enabled: "",
  //时间范围
  date:[]
};
let goodsForm = {
  //发货渠道ID
  deliveryChannelId:0,
  //发货渠道名称
  deliveryChannelName:'',
  //商品资费类型ID
  goodsCostType:'',
  //商品资费类型名称
  goodsCostTypeName:'',
  //批内商品数量最小占比(%)
  minGoodNumPop:'',
  //批内商品数量最大占比(%)
  maxGoodNumPop:'',
  //每单内商品最小个数
  minGoodsNum:0,
  //每单内商品最大个数
  maxGoodsNum:0,
}
//发货渠道基本信息表单
let baseForm = {
  id:0,
  //所属门店名称
  storeName:[],
  //所属门店ID
  storeId:[],
  //渠道名称
  channelName:'',
  //每批最小重量
  minWeight:'0',
  //允许电话重复
  phoneRepeatAble:false,
  //电话最大重复次数
  phoneRepeatLimit:'0',
  //每批最大重量
  maxWeight:'0',
  //允许姓名重复
  nameRepeatAble:false,
  //姓名最大重复次数
  nameRepeatLimit:'0',
  //发货日
  deliveryDate:'',
  //允许地址重复
  addressRepeatAble:false,
  //地址最大重复次数
  addressRepeatLimit:'0',
  //备注
  note:'',
  //商品收费信息
  channelCostInfos:[goodsForm],
  //申报前是否需要身份证
  idCardNeeded:false,
  //是否自动审批
  autoSplitToBatch:false,
  //是否启用
  enabled:true,
};
import myHeader from "@/components/pageHEader/pageHeader";
import { mapGetters } from "vuex";
import {
  getPostage,
} from "@/api/baseconfig/postage";
import {
  getChannel,
  addChannel,
  delChannel,
  modChannel,
  disableOrEnableChannel,
  getChannelById
} from "@/api/intermodals/channel";
export default {
  name: "channel",
  components: {
    myHeader,
  },
  data() {
    return {
      pageSize: 20,
      currentPage: 1,
      total: 0,
      data: [],
      //表格选中
      multipleSelection: [],
      //搜索
      search: this.cloneObj(search),
      //对话框
      dialogFormVisible: false,
      title: "添加",
      baseForm:{},
      baseFormOptions:{
        allGoods:[]
      },
      isPurchase:true,
      baseFormRules:{
        //所属门店
        storeName: [this.$RegExp.required("所属门店不能为空")],
        //渠道名称
        channelName: [this.$RegExp.required("渠道名称不能为空")],
        //每批最小重量不能为空
        minWeight: [this.$RegExp.required("每批最小重量不能为空")],
        //每批最大重量不能为空
        maxWeight: [this.$RegExp.required("每批最大重量不能为空")],
      },
    };
  },
  computed: {
    ...mapGetters(["stores","roles"]),
  },
  created() {},
  mounted() {
    this.getChannel();
    this.baseForm = this.cloneObj(baseForm)
    this.getPostage()
  },
  methods: {
    handleSizeChange(val) {
      this.pageSize = val;
      this.getChannel()
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.getChannel()
    },
    //获取所有商品收费类型
    getPostage() {
      let query = {
        pageNum: 1,
        pageSize: 1000,
      };
      getPostage(query).then((resp) => {
        this.baseFormOptions.allGoods =  resp.data.records
      });
    },
    //重置表单信息
    restForm() {
      this.$nextTick(() => {
        if (this.$refs.baseForm) this.$refs.baseForm.resetFields();
      });
    },
    handleBeforeUpdate(){
      if (!this.multipleSelection.length) {
        this.tip();
        return;
      }
      if (this.multipleSelection.length > 1) {
        this.tip("只能勾选表格中的一条数据");
        return;
      }
      this.handleAddUpdate(this.multipleSelection[0])
    },
    //添加、修改
    handleAddUpdate(row) {
      //修改处理
      if (row) {
        this.title = "修改";
        getChannelById(row.id).then(resp=>{
          let row = resp.data
          //将数据复制给form
          this.handleModform(row, this.baseForm);
          this.baseForm.storeId = this.baseForm.storeId.map(item=>parseInt(item))
          this.dialogFormVisible = true;
        })
      } else {
        this.baseForm = this.cloneObj(baseForm);
        this.title = "添加";
        this.dialogFormVisible = true;
      }
    },
    //刷新
    getChannel() {
      let query = {
        pageNum: this.currentPage,
        pageSize: this.pageSize,
        info: this.search.info,
        autoSplitToBatch:this.search.autoSplitToBatch,
        idCardNeeded:this.search.idCardNeeded,
        enabled:this.search.enabled,
        startDate: this.search.date[0]?this.search.date[0]+' 00:00:00':'',
        endDate: this.search.date[1]?this.search.date[1]+' 23:59:59':'',
      };
      getChannel(query).then((resp) => {
        this.data =  resp.data.records
        this.total = resp.data.total;
      });
    },
    //表格双击修改
    handleRowDbclick(row) {
      this.handleAddUpdate(row);
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    //选择商品收费类型名称
    handleGoodsChange(row){
      row.deliveryChannelName = this.baseForm.channelName
      this.baseFormOptions.allGoods.forEach(item=>{
        if (row.goodsCostType==item.id){
          row.goodsCostTypeName = item.name
        }
      })
    },
    //选择仓库名称
    handleStoreChange(val){
      let arr = []
      this.stores.forEach(item=>{
        val.forEach(id=>{
          if(id == item.id){
            arr.push(item.name)
          }
        })
      })
      this.baseForm.storeName = arr
    },
    //运单收费信息
    addGoods() {
      if (this.title == '修改'){
        goodsForm.deliveryChannelId = this.baseForm.channelCostInfos.filter(item=>{return item})[0].deliveryChannelId
      }
      this.baseForm.channelCostInfos.push(this.cloneObj(goodsForm));
    },
    //删除运单收费信息
    deleteGoods(index) {
      if(this.baseForm.channelCostInfos.length>1){
        this.confirm().then(() => {
          this.baseForm.channelCostInfos.splice(index, 1);
        });
      }else{
        this.$message.error('删除失败，商品收费类型至少有一条内容！')
      }
    },
    //确定
    submit() {
      this.$refs["baseForm"].validate((valid) => {
        if (valid) {
          let submit = Object.assign(
            this.baseForm
          );
          let request;
          if (this.title == "添加") {
            if(submit.channelCostInfos.length<=1 && (submit.channelCostInfos[0].goodsCostTypeName=="" || submit.channelCostInfos[0].goodsCostType=="")){
              submit.channelCostInfos = []
              request = addChannel(submit);
            }else{
              request = addChannel(submit);
            }
          } else {
            request = modChannel(submit);
          }
          request.then((resp) => {
            this.$message.success(resp.message || "成功");
            this.dialogFormVisible = false;
            this.getChannel();
          });
        }
      });
    },
    //查看
    view() {
      this.handleBeforeUpdate();
      this.title = '查看'
    },
    //删除
    delChannel() {
      if (!this.multipleSelection.length) {
        this.tip();
        return;
      }
      this.confirm().then(() => {
        delChannel(this.multipleSelection.map((item) => item.id)).then(
          (resp) => {
            this.$message.success(resp.message || "成功");
            this.getChannel();
          }
        );
      });
    },
    //启用或禁用
    enabled(enabled) {
      if (!this.multipleSelection.length) {
        this.tip();
        return;
      }
      let ids = this.multipleSelection.map((item) => item.id);
      let tip;
      if (enabled) {
        tip = "此操作将启用渠道信息, 是否继续?";
      } else {
        tip = "此操作将禁用渠道信息, 是否继续?";
      }
      this.confirm(tip).then(() => {
        disableOrEnableChannel(ids,{enabled}).then((resp) => {
          this.$message.success(resp.message || "成功");
          this.getCustomer();
        });
      });
    },
    getChannelCostInfos(row,column){
      let getChannelList = []
      for(let i = 0; i < row.channelCostInfos.length;i++){
        getChannelList.push(row.channelCostInfos[i].goodsCostTypeName)
      }
      return getChannelList.join()
    },
  },
};
</script>

<style scoped lang='scss'>
.tdItem {
  line-height: 25px;
}
</style>
